package com.scwatch.core.html;

import com.scwatch.common.file.FileHandler;
import com.scwatch.common.freemarker.Freemarkers;
import com.scwatch.common.web.PathResolver;
import com.scwatch.core.domain.*;
import com.scwatch.core.service.TaskService;
import com.scwatch.core.support.Context;
import com.scwatch.core.support.ForeContext;
import com.scwatch.core.support.TitleText;
import freemarker.ext.servlet.FreemarkerServlet;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;

import java.io.IOException;
import java.util.*;

/**
 * PInfo
 * 
 * @author gjl
 * 
 */
public abstract class PInfo {
	public static void makeHtml(Info info, Configuration config, PathResolver pathResolver, TaskService taskService,
			Integer taskId,Map<String,Object> dataMap) throws IOException, TemplateException {
		if (info == null) {
			return;
		}
		deleteHtml(info, pathResolver);
		info.updateHtmlStatus();
//		if (!info.isNormal() || !info.getGenerate()) {
//			// 不需要生成
//			return;
//		}
        if (!info.getGenerate()) {
			// 不需要生成
			return;
		}
		Context.setMobile(false);
		try {
			doMakeHtml(info, config, pathResolver, taskService, taskId,dataMap);
			// 生成手机端HTML
			if (info.getSite().getMobilePublishPoint() != null
					&& info.getSite().getMobilePublishPoint().getId() != info.getSite().getHtmlPublishPoint().getId()
					&& StringUtils.isNotBlank(info.getSite().getMobileDomain())) {
				Context.setMobile(true);
				doMakeHtml(info, config, pathResolver, taskService, taskId,dataMap);
			}
		} finally {
			Context.resetMobile();
		}
	}

	private static void doMakeHtml(Info info, Configuration config, PathResolver pathResolver, TaskService taskService,
			Integer taskId,Map<String,Object> dataMap) throws IOException, TemplateException {

		Site site = info.getSite();
		Node node = info.getNode();
		List<TitleText> textList = info.getTextList();
		Template template = config.getTemplate(info.getTemplate());
		Map<String, Object> rootMap = new HashMap<String, Object>();
		rootMap.put(FreemarkerServlet.KEY_APPLICATION, Collections.EMPTY_MAP);
		rootMap.put(FreemarkerServlet.KEY_SESSION, Collections.EMPTY_MAP);
		rootMap.put(FreemarkerServlet.KEY_REQUEST, Collections.EMPTY_MAP);
		rootMap.put(Freemarkers.KEY_PARAMETERS, Collections.EMPTY_MAP);
		rootMap.put(Freemarkers.KEY_PARAMETER_VALUES, Collections.EMPTY_MAP);
		rootMap.put("info", info);
		rootMap.put("node", node);
		TitleText titleText;
		List<String> items = new ArrayList<String>(1);
		items.add(null);
		Pageable pa;
		int total = textList.size();
		PublishPoint publishPoint = Context.isMobile() ? info.getSite().getMobilePublishPoint() : info.getSite()
				.getHtmlPublishPoint();
		FileHandler fileHandler = publishPoint.getFileHandler(pathResolver);
		rootMap.put("pubPointUrl",fileHandler.getPrefix());
		for (int page = 0; page < total && taskService.isRunning(taskId); page++) {
			titleText = textList.get(page);
			String filename = info.getUrlStatic(page, false, true, Context.isMobile());
			if (page == 0) {
				if (Context.isMobile()) {
					info.getDetail().setMobileHtml(filename);
				} else {
					info.getDetail().setHtml(filename);
				}
				info.setHtmlStatus(Node.HTML_GENERATED);
			}
			rootMap.put("title", titleText.getTitle());
			rootMap.put("text", titleText.getText());
			items.set(0, titleText.getText());
			pa = new PageRequest(page, 1);
			Page<String> pagedList = new PageImpl<String>(items, pa, total);
			String url = info.getUrlStatic(page);
			ForeContext.setData(rootMap, site, null, null, null, null, null, null, url);
			ForeContext.setPage(rootMap, page, info, pagedList);
//            System.out.println("infoId:"+info.getId());
            if(info.getStatus()==null || !"A".equals(info.getStatus())){
                if (info.getRefSpec() != null) {         //专题
//                    rootMap.put("special", info.getRefSpec());
//                    //生成分享h5
//                    String shared = node.getSite().getTemplate("/h5/opic_page_shared.html");
//                    Template specsharedTemplate = config.getTemplate(shared);
//                    String specsharedFileName = filename.replaceFirst(".json", "_pre.html");
//                    fileHandler.storeFile(specsharedTemplate, rootMap, specsharedFileName);
                } else if (info.getRefLive() != null) {   //直播
//                    List<LiveBroadcastRoom> roomList = (List<LiveBroadcastRoom>) dataMap.get("roomList");
//                    rootMap.put("roomList", roomList);
//                    //直播分享页面
//                    String shared = node.getSite().getTemplate("/h5/live_broadcast_shared.html");
//                    Template sharedTemplate1 = config.getTemplate(shared);
//                    String sharedFileName = filename.replaceFirst(".json", "_pre.html");
//                    fileHandler.storeFile(sharedTemplate1, rootMap, sharedFileName);
                } else if (info.getRefLive() == null && info.getRefInfo() == null && info.getRefSpec() == null && info.getNewsType() != null
                        && StringUtils.isBlank(info.getLink())) {
					Info newInfo = (Info)dataMap.get("newInfo");
					rootMap.put("newInfo",newInfo);
                    //生成分享h5
                    String shared = node.getSite().getTemplate("/h5/shared_h5.html");
                    Template sharedTemplate1 = config.getTemplate(shared);
                    String sharedFileName = filename.replaceFirst(".json", "_pre.html");
                    fileHandler.storeFile(sharedTemplate1, rootMap, sharedFileName);
                }
            }else if(info.getStatus()!=null && "A".equals(info.getStatus())) {
                if (info.getRefSpec() != null) {         //专题
//                    rootMap.put("special", info.getRefSpec());
//
//                    //生成分享h5
//                    String shared = node.getSite().getTemplate("/h5/opic_page_shared.html");
//                    Template specsharedTemplate = config.getTemplate(shared);
//                    String specsharedFileName = filename.replaceFirst(".json", "_shared.html");
//                    fileHandler.storeFile(specsharedTemplate, rootMap, specsharedFileName);
//                    //预览页面
//                    fileHandler.storeFile(specsharedTemplate, rootMap, specsharedFileName.replace("_shared.html","_pre.html"));
//                    String specSharedUrl = info.getDynamicUrl() + specsharedFileName;
//                    //生成 专题新闻
//                    rootMap.put("specSharedUrl", specSharedUrl);
//                    String spec = node.getSite().getTemplate("/json/spec_info.ftl");
//                    Template specTemplate1 = config.getTemplate(spec);
//                    fileHandler.storeFile(specTemplate1, rootMap, filename);

                } else if (info.getRefLive() != null) {   //直播
//                    List<LiveBroadcastRoom> roomList = (List<LiveBroadcastRoom>) dataMap.get("roomList");
//                    rootMap.put("roomList", roomList);
//                    //直播分享页面
//                    String shared = node.getSite().getTemplate("/h5/live_broadcast_shared.html");
//                    Template sharedTemplate1 = config.getTemplate(shared);
//                    String sharedFileName = filename.replaceFirst(".json", "_shared.html");
//                    fileHandler.storeFile(sharedTemplate1, rootMap, sharedFileName);
//                    //预览页面
//                    fileHandler.storeFile(sharedTemplate1, rootMap, sharedFileName.replace("_shared.html","_pre.html"));
//                    String liveSharedUrl = info.getDynamicUrl() + sharedFileName;
//                    rootMap.put("liveSharedUrl", liveSharedUrl);
//
//                    fileHandler.storeFile(template, rootMap, filename);
                } else if (info.getRefLive() == null && info.getRefInfo() == null && info.getRefSpec() == null && info.getNewsType() != null
                        && StringUtils.isBlank(info.getLink())) {
					Info newInfo = (Info)dataMap.get("newInfo");
					rootMap.put("newInfo",newInfo);

                    //生成正文h5
                    String h5 = node.getSite().getTemplate("/h5/info_h5.html");
                    Template h5Template1 = config.getTemplate(h5);
                    String h5FileName = filename.replaceFirst(".json", "_h5.html");
                    fileHandler.storeFile(h5Template1, rootMap, h5FileName);

                    //生成分享h5
                    String shared = node.getSite().getTemplate("/h5/shared_h5.html");
                    Template sharedTemplate1 = config.getTemplate(shared);
                    String sharedFileName = filename.replaceFirst(".json", "_shared.html");
                    fileHandler.storeFile(sharedTemplate1, rootMap, sharedFileName);
                    //预览页面
                    fileHandler.storeFile(sharedTemplate1, rootMap, sharedFileName.replace("_shared.html","_pre.html"));

                    String rootUrl = url.replaceFirst("/", "");
                    rootUrl = "/" + rootUrl.substring(0, rootUrl.indexOf("/"));
                    String h5Url = rootUrl + h5FileName;
                    String sharedUrl = rootUrl + sharedFileName;

                    rootMap.put("h5Url", h5Url);
                    rootMap.put("sharedUrl", sharedUrl);
                    //生成新闻详情
                    fileHandler.storeFile(template, rootMap, filename);
                }
            }

			taskService.add(taskId, 1);
		}
	}

	public static void deleteHtml(Info info, PathResolver pathResolver) {
//		String html = info.getHtml();
//		FileHandler fileHandler = info.getSite().getHtmlPublishPoint().getFileHandler(pathResolver);
//		PNode.deleteHtml(html, fileHandler);
//		if (info.getDetail() != null) {
//			info.getDetail().setHtml(null);
//		}
//
//		String mobileHtml = info.getMobileHtml();
//		fileHandler = info.getSite().getMobilePublishPoint().getFileHandler(pathResolver);
//		PNode.deleteHtml(mobileHtml, fileHandler);
//		if (info.getDetail() != null) {
//			info.getDetail().setMobileHtml(null);
//		}
        if((Info.CLEAR.equals(info.getStatus())||Info.DELETED.equals(info.getStatus())) && info.getNewsType()!=null && info.getNewsType().intValue()<=6 && info.getRefSpec()==null && info.getRefLive()==null){ //不是审核通过的状态，删掉静态文件
            String jsonUrl=info.getUrl();
            String h5Url=info.getH5Url();
            String sharedUrl=info.getSharedUrl();
            String preUrl=info.getPreUrl();
            FileHandler fileHandler = info.getSite().getHtmlPublishPoint().getFileHandler(pathResolver);
            boolean flag=false;

            if (StringUtils.isNotBlank(jsonUrl)) {
                 flag=fileHandler.delete(jsonUrl);
            }

            if (StringUtils.isNotBlank(h5Url)) {
                flag=fileHandler.delete(h5Url);
            }

            if (StringUtils.isNotBlank(sharedUrl)) {
                 flag=fileHandler.delete(sharedUrl);
            }

            if(Info.CLEAR.equals(info.getStatus()) && StringUtils.isNotBlank(preUrl)){ //彻底清除时，也清理掉预览html
                 flag=fileHandler.delete(preUrl);
            }
        }
	}
}
